#include "threadPool.h"

int recvn(int sockfd, void *buf,ssize_t length){
    char *p = (char *)buf;
    ssize_t cursize = 0;
    while(cursize < length){
        ssize_t sret =recv(sockfd,p+cursize,length-cursize,0);
        cursize += sret;
    }
    return 0;
}

int recvfile(int sockfd){
    train_t train;
    // 接收火车头
    recvn(sockfd,&train.length,sizeof(train.length));
    recvn(sockfd,train.data,train.length);
    char filename[4096]={0};
    memcpy(filename,train.data,train.length);

    int fd = open(filename,O_RDWR|O_CREAT|O_TRUNC,0666);

    off_t filesize;
    off_t cursize = 0;
    off_t lastsize = 0;

    recvn(sockfd,&train.length,sizeof(train.length));
    recvn(sockfd,train.data,train.length);
    memcpy(&filesize,train.data,train.length);
    printf("filesize:%ld\n",filesize);
    off_t slice = filesize/10000;

    while(1){
        bzero(train.data,sizeof(train.data));
        recvn(sockfd,&train.length,sizeof(train.length));
        if(train.length != 1000){
            printf("train.length : %d\n",train.length);
        }
        if(train.length == 0){
            break;
        }
        cursize += train.length;
        if(lastsize - cursize > slice){
            printf("%5.2lf%%\r",100.0*cursize/filesize);
            fflush(stdout);
            lastsize = cursize;
        }
        recvn(sockfd,train.data,train.length);
        write(fd,train.data,train.length);
    }
    printf("100.00%%\n");
    close(fd);
    return 0;
}

